package com.os.mq;

import cn.hutool.json.JSONUtil;
import com.os.data.DataHashCache;
import com.os.config.ConfigInit;
import com.os.model.LocationMsg;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

/**
 * 接收接口服务定位数据的消息
 * @author 风亦未止
 * @date 2023/5/7 1:03
 */
@Log4j2
@Component
public class LocateListener {
    @Autowired
    private ConfigInit configInit;

    @Autowired
    private MessageProperties messageProperties;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "#{mqConfig.queueName()}"),
            exchange = @Exchange(name = "data_exchange",type = ExchangeTypes.FANOUT)
    ))
    @SneakyThrows
    @SendTo("#{mqConfig.tempQueue()}")
    public Message locateListener(String hash) {
        Integer location = location(hash);
        if( location != -1){
            log.info(hash + "存在~");
            LocationMsg locationMsg = new LocationMsg(configInit.host, location);
            String s = JSONUtil.parse(locationMsg).toString();
            Message message = new Message(s.getBytes(), messageProperties);
            return message;
        }
        return null;
    }

    public Integer location(String hash){
        Integer integer = DataHashCache.dataHashCache.get(hash);
        if( integer == null){
            return -1;
        }
        return integer;
    }
}
